package com.ruoyi.common.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author fanww
 * @version 1.0
 * @description: TODO
 * @date 2023/7/6 21:24
 * @since 1.0
 */
public class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
    private String localDateTimeFormat = "yyyy-MM-dd HH:mm:ss";
    private String localDateTimeFormatToUtc = "yyyy-MM-dd'T'HH:mm:ss";
//    public  CustomLocalDateTimeDeserializer(String localDateTimeFormat){
//        this.localDateTimeFormat=localDateTimeFormat;
//    }
    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String text = p.getText().trim();
        String pattern=localDateTimeFormat;
        if(text.indexOf('T')>-1){
            pattern=localDateTimeFormatToUtc;
        }
        if(isValidTimeFormat(text)){
            pattern="yyyy-MM-dd HH:mm";
        }
        if(isValidDayFormat(text)){
            text+=" 00:00:00";
//            pattern="yyyy-MM-dd 00:00:00";
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);

        return LocalDateTime.parse(text,formatter);
    }

    private boolean isValidDayFormat(String timeStr) {
        Pattern pattern = Pattern.compile("^\\d{4}-\\d{2}-\\d{2}$");
        Matcher matcher = pattern.matcher(timeStr);
        return matcher.matches();
    }

    private boolean isValidTimeFormat(String timeStr) {
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Pattern pattern = Pattern.compile("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}$");
        Matcher matcher = pattern.matcher(timeStr);
        return matcher.matches();
    }
}
